<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="modelForm"
      :before-close="beforeClose"
      :data="tableData"
      :option="tableOption"
      @on-load="onLoad"
      @row-save="saveDataFile"
      @row-update="updateDataFile"
      @refresh-change="onLoad"
      @search-change="searchChange"
    >
      <template slot-scope="{type,size,row}" slot="menu">
        <el-button @click.stop="handleMetadaEdit(row)" icon="el-icon-edit" :size="size" :type="type">编辑</el-button>
        <el-button @click.stop="handleDelMetadata(row)" icon="el-icon-delete" :size="size" :type="type">删除</el-button>
      </template>
      <template slot-scope="{}" slot="imgUrlLabel">
        <span style="color:#F56C6C;margin-right: 4px;">*</span><span>数据文件&nbsp;&nbsp;</span>
      </template>
      <template slot-scope="{row}" slot="imgUrlForm">
        <span v-if="isEdit">{{row.originalName}}</span>
        <el-upload
          class="upload-demo"
          ref="upload"
          :limit="1"
          :headers="headers"
          :data="uploadData"
          :action="url"
          :auto-upload="false"
          :on-success="successUpload"
          :on-exceed="moreFilesTip"
          :on-change="changeFile"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </template>
      <template slot-scope="{}" slot="templateLabel">
        <span style="color:#F56C6C;margin-right: 4px;">*</span><span>选择模板&nbsp;&nbsp;</span>
      </template>
      <template slot-scope="{row}" slot="templateForm">
        <div style="width: 41.5%;float: left">
          <el-select v-model="modelForm.templateId" placeholder="请选择">
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div style="width: 18%;float: left;margin-left:4%;">
          <el-link type="primary" :underline="false" @click.stop="preview">查看模板</el-link>
          <!--<el-button type="primary">查看模板</el-button>-->
        </div>
      </template>
      <template slot-scope="{}" slot="relatedataLabel">
        <span style="color:#F56C6C;margin-right: 4px;">*</span><span>关联元数据&nbsp;&nbsp;</span>
      </template>
      <template slot-scope="{row}" slot="relatedataForm">

        <div style="width: 30%;float: left;">
          <avue-input-tree v-model="modelForm.modelPackageId" placeholder="请选择模型包" type="tree" :props="props" :dic="modelPackageTreeData" @change="changePackage"></avue-input-tree>
        </div>
        <div style="width: 30%;float: left;margin-left:4%;">
          <avue-input-tree v-model="modelForm.modelId" placeholder="请选择元数据" type="tree" :props="metaProps"
                           :dic="modelTreeData" @change="changeModel"></avue-input-tree>
        </div>
        <div style="width: 30%;float: left;margin-left:4%;">
          <el-link type="primary" :underline="false" @click="toMetadata">选不到？请先添加元数据</el-link>
        </div>
      </template>
      <template slot-scope="{row}" slot="modelPackageIdForm">
        <div>
          <avue-crud
            ref="property"
            v-model="propertyForm"
            :data="propertyList"
            :option="propertyOption"
          >
            <template slot="property" slot-scope="scope">

              <div v-if="scope.row.typeName === 'string'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <avue-input v-model="scope.row.property" placeholder="请输入值"></avue-input>
              </div>
              <div v-if="scope.row.typeName === 'date'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <avue-date v-model="scope.row.property" type="datetime" format="yyyy年MM月dd日 hh:mm:ss"
                           value-format="timestamp" placeholder="请选择日期"></avue-date>
              </div>
              <div v-if="scope.row.typeName === 'int'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <el-input-number v-model="scope.row.property" ></el-input-number>
              </div>
              <div v-if="scope.row.typeName === 'float'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;padding-top: 5px;">*</span>
                <el-input-number v-model="scope.row.property" :precision="2" :step="0.1"></el-input-number>
              </div>
              <div v-if="scope.row.typeName === 'boolean'" style="display: flex;">
                <span v-if="!scope.row.isOptional" style="color: #F56C6C;margin-right: 5px;">*</span>
                <avue-radio v-model="scope.row.property" :dic="dic"></avue-radio>
              </div>
            </template>
          </avue-crud>
        </div>

      </template>
    </avue-crud>
    <el-dialog class="avue-dialog avue-crud__dialog" custom-class="dialog-width" append-to-body title="预览" :visible.sync="previewVisible">
      <div style="text-align: center;margin-bottom: 20px;">
        <img style="max-width: 600px;" :src="imgUrl" v-if="pictureTypes.indexOf(tempType) > -1">
        <video :src="imgUrl" controls="controls" v-if="tempType === 'MPEG'"></video>
      </div>
    </el-dialog>
  </basic-container>
</template>
<script>
  import {
    getModelDetail,
    getMetadataPackageList
  } from '@/api/metadata/model';
  import {
    getMetaDataList
  } from '@/api/metadata/metadata';
  import {
    getMetaList,
    getFileList,
    saveDataFile,
    removeDataFile
  } from '@/api/dataMaintenance/fileManage';
  import {getList} from '@/api/metadata/grade';
  import {getLabelTree} from '@/api/metadata/label';
  import {listLabeltype} from '@/api/metadata/labeltype';
  import {
    getTemplateList
  } from '@/api/dataMaintenance/fileTemplate';
  import {
    getMetadataDetail,
    saveMetadata,
    deleteMeta
  } from '@/api/metadata/metadata';
  import {
    downLoadTemplate
  } from '@/api/dataMaintenance/fileTemplate';
  export default {
    data() {
      return {
        pictureTypes:['BMP','bmp','JPG','jpg','JPEG','jpeg','PNG','png','GIF','gif'],
        previewVisible:false,
        url:'',
        imgUrl: '',
        tempType: '',
        uploadData: {
          attach:''
        },
        headers:{},
        templateList: [],
        page: {},
        currentDir: null,
        tableData: [],
        isEdit: false,
        propertyForm: {},
        propertyList: [],
        metaModelId: '',
        metaPackageId: '',
        propertyOption: {
          editBtn: false,
          delBtn: false,
          header: false,
          menu: false,
          column: [
            {
              label:'属性名称',
              prop:'name',
            },
            {
              label:'类型',
              prop:'typeName',
              type:'select',
              dicData: []
            },
            {
              label:'描述',
              prop:'description',
              type: "textarea"
            },
            {
              label:'属性值',
              prop:'property',
            },
          ]
        },
        props: {
          label: "name",
          value: "id"
        },
        metaProps: {
          label: 'displayText',
          value: 'guid'
        },
        modelTreeData: [],
        modelPackageTreeData: [],
        tableOption: {
          addBtnText:'上传',
          addTitle: '文件上传',
          //addBtn:false,
          editBtn:false,
          delBtn:false,
          // height: 'auto',
          // calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: false,
          //editBtn: false,
          //addBtn: false,
          // viewBtn: true,
          // delBtn: false,
          // menuWidth: 350,
          dialogClickModal: false,
          menuWidth: 180,
          column: [
            {
              label: '文件名称',
              prop: 'name',
              search: true,
              display: false
            },
            {
              label: '关联元数据',
              prop: 'metaName',
              display: false
            },
            {
              label: '文件类型',
              prop: 'fileType',
              display: false
            },
            {
              label: '入库状态',
              prop: 'putStatus',
              search: true,
              display: false
            },
            {
              label: '提供部门',
              prop: 'dep',
              search: true,
              display: false
            },
            {
              label: '关键字',
              prop: 'keyss',
              search: true,
              display: false
            },
            {
              label: '数据领域',
              prop: 'dataDomain',
              search: true,
              display: false
            },
            {
              label: '所属行业',
              prop: 'business',
              search: true,
              display: false
            },
            {
              label: '汇聚时间',
              prop: 'putTime',
              display: false
            }
          ],
          group: [
            {
              label: '基础信息',
              prop: 'baseInfo',
              icon: 'el-icon-tickets',
              labelWidth:110,
              column: [
                {
                  label: '数据文件',
                  prop: 'imgUrl'
                },
                {
                  label: "选择模板",
                  prop: "template",
                  span: 24
                },
                {
                  label: "关联元数据",
                  prop: "relatedata",
                  span: 24
                },
              ]
            },
            {
              label: '元数据信息维护',
              collapse: false,
              prop: 'metaInfo',
              icon: 'el-icon-tickets',
              labelWidth:110,
              column: [
                {
                  label: "名称",
                  prop: "name",
                  // rules: [{
                  //   required: true,
                  //   message: "请输入名称",
                  //   trigger: "blur"
                  // }]
                },
                {
                  label: "代码",
                  prop: "code",
                  // rules: [{
                  //   required: true,
                  //   message: "请输入代码",
                  //   trigger: "blur"
                  // }],
                  editDisabled:true
                },
                {
                  label:'标签',
                  prop:'labels',
                  type:'tree',
                  multiple:true,
                  props: {
                    label: "name",
                    value: "id"
                  },
                  dicData: []
                },
                {
                  label:'分级',
                  prop:'grade',
                  type:'tree',
                  props: {
                    label: "name",
                    value: "id"
                  },
                  dicData: []
                },
                {
                  label:'分类',
                  prop:'classification',
                  type:'tree',
                  props: {
                    label: "name",
                    value: "id"
                  },
                  dicData: []
                },
                {
                  label: "描述",
                  prop: "remark",
                  type: "textarea",
                  minRows: 2,
                  span: 24
                },
                {
                  label: '元模型',
                  prop: 'modelPackageId',
                  span:24
                }
              ]
            }
          ]
        },
        modelForm: {
          'modelId': '',
          'modelPackageId': '',
          'templateId': ''
        },
        templates: [],
        entityAttr: {
          'name': '',
          'owner': '',
          'description': ''
        },
        // 默认写死
        modelPackageId: '',
        modelId: '',
        currentCategoryId: '',
        typeName: 'DATAFILE',
        entityFilters: null,
        file: null
      }
    },
    mounted() {
      //this.getModelDetail(this.modelId);
      this.getGradeList();
      this.getLabelList();
      this.getClassfication();
      this.getAllPackageList();
      this.getTemplateList();
    },
    methods: {

      saveDataFile(row,done,loading) {
        if(!this.isEdit) {
          if(!this.file){
            this.$message.error('请选择数据文件');
            loading();
            return;
          }
        }
        if(!this.modelForm.templateId){
          this.$message.error('请选择模板');
          loading();
          return;
        }
        if(!this.modelForm.modelId){
          this.$message.error('请选择元数据');
          loading();
          return;
        }
        let _t = this;
        let modelId = this.modelForm.modelId;
        let meta = this.modelTreeData.filter(function (item) {
          return item.guid === modelId ;
        });
        let templateId = this.modelForm.templateId;
        let template = this.templateList.filter(function (item) {
          return item.id === templateId;
        });
        let dep = '';
        let keyss = '';
        let business = '';
        let dataDomain = '';
        this.propertyList.forEach(item => {
          if(item.name === 'KEYWORDS'){ //关键字
            keyss = item['property']
          }
          if(item.name === 'INDUSTRYSECTOR'){ // 数据领域
            dataDomain = item['property']
          }
          if(item.name === 'FILEORG'){ // 部门
            dep = item['property']
          }

          if(item.name === 'FILESECTOR'){ // 行业
            business = item['property']
          }
        });
        let obj = {
          metaId:modelId,
          metaName:meta[0]['attributes']['name'],
          dep:dep,
          keyss:keyss,
          business:business,
          dataDomain:dataDomain,
          domaina:this.modelForm.modelPackageId
        };
        if(this.file){
          obj['name'] = this.file.name
        }
        if(templateId){
          obj['templateId'] = templateId;
          obj['fileType']= template[0]['originalName'].split('.')[1];
        }
        if(this.isEdit) {
          obj['id'] = row['id'];
        }
        this.uploadData.attach = JSON.stringify(obj);
        const formData = new FormData();
        formData.append('attach',this.uploadData.attach);
        if(this.file){
          formData.append('file', this.file.raw, this.file.name);
        }
        saveDataFile(formData).then( res => {
          this.successUpload();
          done();
        });
        // 更新元数据
        this.handleMetadaUpdate(row);
      },
      updateDataFile(row,index,done,loading) {
        this.saveDataFile(row,done,loading)
      },
      successUpload(res) {
        this.getFileList();
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      },
      changeFile(file, fileList) {
        this.file = file;
      },
      moreFilesTip() {
        this.$message.error('只能选择一个文件');
      },
      getTemplateList() {
        getTemplateList({
          current: 1,
          size: 1000
        }).then( res => {
          const data = res.data.data;
          this.templateList = data.records;
        }).catch( error => {

        });
      },
      changePackage(e,v) {
        if(e){
          this.manageDB(e);
        }
      },
      manageDB(id) {
        let param = {
          "excludeDeletedEntities":true,
          "includeSubClassifications":true,
          "includeSubTypes":true,
          "includeClassificationAttributes":true,
          "entityFilters":null,
          "tagFilters":null,
          "attributes":[],
          "limit":10,
          "offset":0,
          "query":null,
          "typeName":null,
          "classification":null,
          "termName":id
        };
        getMetaDataList(param).then( res => {
          this.modelTreeData = res['data']['data']['entities'];
        });
      },
      toMetadata() {
        this.$router.push({
          path: "/metadata/mange"
        });
      },
      changeModel(e) {
        if(e) {
          this.getMetadataDetail(e);
        }
      },
      getMetadataDetail(id) {
        let _t = this;
        getMetadataDetail(id).then(res => {
          if(res['status'] === 200 ) {
            let entity = res['data']['entity'];
            this.entityAttr = res['data']['entity']['attributes'];
            // setTimeout(()=>{
              _t.modelForm.name = entity['attributes']['name'];
              _t.modelForm.code = entity['attributes']['qualifiedName'];
              _t.modelForm.remark = entity['attributes']['description'];
              _t.modelForm.labels = entity['labels'] || [];
              if(!!entity['customAttributes']){
                _t.modelId = entity['customAttributes']['modelId'];
                _t.metaModelId = entity['customAttributes']['modelId'];
                _t.metaPackageId = entity['customAttributes']['modelPkgId'];
                _t.modelForm.classification = entity['customAttributes']['classification'];
                _t.modelForm.grade = entity['customAttributes']['grade'];
                _t.getModelDetail(_t.modelId);
              }
            // },0)
            this.tableOption.group[1].collapse = true;
          }
        });
      },
      getAllPackageList() {
        getMetadataPackageList('').then(res => {
          this.modelPackageTreeData = res.data.data.concat([]);
          //this.handleModelMap(this.modelPackageTreeData);
        });
      },
      onLoad() {
        this.getFileList();
      },
      handleNodeClick(data) {
        this.currentDir = data;
        this.onLoad();
      },
      searchChange(params, done) {
        this.entityFilters = null;
        let keys = Object.keys(params);
        if (keys.length === 0) {
          this.entityFilters = null;
        } else {
          this.entityFilters = {
            condition: 'AND',
            criterion: keys.map(item => {
              return {
                attributeName: item,
                operator: 'contains',
                attributeValue: params[item]
              }
            })
          }
        }
        this.getMetaList();
        done();
      },
      getFileList() {
        this.Loading = true;
        getFileList({
          current: this.page.currentPage,
          size: this.page.pageSize
        }).then( res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.tableData = data.records;
          this.Loading = false;
        }).catch( error => {
          this.Loading = false;
        });
      },
      getMetaList() {
        let obj = {
          "excludeDeletedEntities": true,
          "includeSubClassifications": true,
          "includeSubTypes": true,
          "includeClassificationAttributes": true,
          "entityFilters": this.entityFilters,
          "tagFilters": null,
          "attributes": ["FILENAME", "FILEORG", "FILEPATH", "FILESECTOR", "FILESIZE", "FILESTATUS", "FILETYPE", "INDUSTRYSECTOR", "KEYWORDS", "OWNER"],
          "limit": 10,
          "offset": 0,
          "query": null,
          "typeName": "DATAFILE",
          "classification": null,
          "termName": "1402513162386722817"
        }
        getMetaList(obj).then(res => {
          this.tableData = res['data']['data']['entities'];
        }).catch(
          this.tableData = []
        )
      },
      getModelDetail(id) {
        getModelDetail(id).then( res => {
          if(res['data']['code'] === 200) {
            if(res['data']['data']['source'] && res['data']['data']['source'] !== '') {
              let model = JSON.parse(res['data']['data']['source']);
              this.propertyList = model['attributeDefs'];
              this.propertyList.forEach( item => {
                if(item['typeName'] === 'date') {
                  item['property'] = new Date().getTime();
                }
              });

              this.propertyList.forEach(item => {
                item['property'] = this.entityAttr[item['name']];
              });

            }
          }

        });
      },
      getGradeList() {
        getList().then(res => {
          this.tableOption.group[1].column[3].dicData = res['data']['data']['records']
        });
      },
      getLabelList() {
        getLabelTree().then(res => {
          this.tableOption.group[1].column[2].dicData = this.translateTreeData(res['data']['children'] || [])
        });
      },
      translateTreeData(treeData){
        let newTreeData = [];
        treeData.forEach(
          item => {
            let el = {
              ...item.label
            }
            if(item.children && item.children.length){
              el['children'] = this.translateTreeData(item['children']);
            }
            newTreeData.push(el);
          }
        )
        return newTreeData;
      },
      getClassfication() {
        listLabeltype().then(res => {
          this.tableOption.group[1].column[4].dicData = res['data']['data']['records']
        });
      },
      handleMetadataSave(row,done,loading) {
        let attr = {
          'name':row['name'],
          'qualifiedName':row['code'],
          'description':row['remark']
        };
        let propertyMap = {};
        let isAllRequireHasValue = true;
        let tempName = '';
        this.propertyList.forEach(item => {
          propertyMap[item['name']] = item['property'];
          if(!item['isOptional'] && (item['property'] === undefined || item['property'] === '' || item['property'] === null )){
            isAllRequireHasValue = false;
            tempName = item['name'];
          }
        });
        if(!isAllRequireHasValue) {
          this.$message.error(`${tempName}属性值必填`);
          loading();
          return;
        }
        let obj = {
          'categoryId':this.currentCategoryId,
          "entity": {
            "entity": {
              "attributes": {
                ...attr,
                ...propertyMap
              },
              "guid": -1,
              "typeName": this.typeName,
              "customAttributes": {
                "grade": row['grade'],
                "modelPkgId":this.modelPackageId,
                "modelId":this.modelId,
                "classification":row['classification']
              },
              labels: this.modelForm.labels
            }
          }
        };
        saveMetadata(obj).then( res => {
          if(res['data']['code'] === 200) {
            done();
            this.getMetaList();
          }
        }).catch( res => {
          loading();
        });

      },
      handleMetadaUpdate(row) {
        let attr = {
          'name':row['name'],
          'qualifiedName':row['code'],
          'description':row['remark']
        };
        let propertyMap = {};
        let isAllRequireHasValue = true;
        let tempName = '';
        this.propertyList.forEach(item => {
          propertyMap[item['name']] = item['property'];
          if(!item['isOptional'] && (item['property'] === undefined || item['property'] === '' || item['property'] === null)){
            isAllRequireHasValue = false;
            tempName = item['name'];
          }
        });
        // if(!isAllRequireHasValue) {
        //   this.$message.error(`${tempName}属性值必填`);
        //   return;
        // }
        let obj = {
          'categoryId':row['modelPackageId'],
          "entity": {
            "entity": {
              "attributes": {
                ...attr,
                ...propertyMap
              },
              "guid": row['modelId'],
              "typeName": this.typeName,
              "customAttributes": {
                "grade": row['grade'],
                "modelPkgId":this.metaPackageId,
                "modelId":this.metaModelId,
                "classification":row['classification']
              },
              labels: this.modelForm.labels
            }
          }
        };
        saveMetadata(obj).then( res => {

        }).catch( res => {

        });
      },
      handleMetadaEdit(row){
        let _t = this;
        this.isEdit = true;
        this.$refs.crud.rowEdit(row);
        _t.modelForm.templateId = row['']
        _t.modelForm.modelPackageId = row['domaina'];
        _t.modelForm.modelId = row['metaId'];
        getMetadataDetail(row['metaId']).then(res => {
          if(res['status'] === 200 ) {
            let entity = res['data']['entity'];
            this.entityAttr = res['data']['entity']['attributes'];

            _t.$refs.crud.rowEdit(row);
            setTimeout(()=>{
              _t.modelForm.name = _t.entityAttr['name'];
              _t.modelForm.code = _t.entityAttr['qualifiedName'];
              _t.modelForm.remark = _t.entityAttr['description'];
              _t.modelForm.labels = entity['labels'] || [];
              _t.typeName = entity['typeName'];
              if(!!entity['customAttributes']){
                let modelId = entity['customAttributes']['modelId'];
                _t.metaModelId = entity['customAttributes']['modelId'];
                _t.metaPackageId = entity['customAttributes']['modelPkgId'];
                console.log(_t.metaModelId)
                _t.modelForm.classification = entity['customAttributes']['classification'];
                _t.modelForm.grade = entity['customAttributes']['grade'];
                this.getModelDetail(modelId);
              }
            },0)
          }
        });
        // this.catalogForm.databaseType = row['globalParamMap']['datasourcetypekey'];
        //  this.datasourceTypeChange(row);
        // this.catalogForm.version = row['globalParamMap']['version'];

      },
      handleDelMetadata(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            removeDataFile(row.id).then(res => {
              if(res['data']['code'] === 200){
                this.$message.success('删除成功');
                this.getFileList();
              } else {
                this.$message.error(res.data.msg)
              }

            }).catch(e => {
              this.$message.error(e.msg || '')
            })
          })
      },
      beforeClose(done) {
        let _t = this;
        _t.propertyList = [];
        _t.modelForm.templateId = '';
        _t.modelForm.modelId = '';
        _t.modelForm.modelPackageId = '';
        _t.modelForm.name = '';
        _t.modelForm.code = '';
        _t.modelForm.remark = '';
        _t.modelForm.classification = '';
        _t.modelForm.grade = '';
        _t.modelForm.labels = [];
        _t.isEdit = false;
        _t.tableOption.group[1].collapse = false;
        done();
      },
      preview() {
        if(!this.modelForm.templateId) {
          this.$message.error('请选择模板');
          return;
        }
        let templateId = this.modelForm.templateId;
        let templates = this.templateList.filter(function (item) {
          return item.id === templateId;
        });
        let row = templates[0];
        this.tempType = row['temType'];
        downLoadTemplate({id:row['id']}).then( res => {
          const content = res.data
          const blob = new Blob([content])
          const file = row.originalName
          this.imgUrl = URL.createObjectURL(blob);
          this.previewVisible = true;
        });
      }
    }
  }
</script>
